package com.crm.api.service.impl;

import com.crm.api.mapper.BusinessMapper;
import com.crm.api.mapper.CustomerMapper;
import com.crm.api.mapper.WorkOrderMapper;
import com.crm.api.service.DashboardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 仪表板服务实现类
 */
@Slf4j
@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Override
    public Map<String, Object> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 客户总数
            Integer customerCount = customerMapper.getActiveCount();
            stats.put("customerCount", customerCount != null ? customerCount : 0);
            
            // 业务总数
            Map<String, Object> businessParams = new HashMap<>();
            Integer businessCount = businessMapper.countBusinesses(businessParams);
            stats.put("businessCount", businessCount != null ? businessCount : 0);
            
            // 工单总数
            Map<String, Object> orderParams = new HashMap<>();
            Integer orderCount = workOrderMapper.countWorkOrders(orderParams);
            stats.put("orderCount", orderCount != null ? orderCount : 0);
            
            // 总营收（计算所有已完成业务的金额总和）
            BigDecimal totalRevenue = businessMapper.getTotalRevenue();
            stats.put("totalRevenue", totalRevenue != null ? totalRevenue : BigDecimal.ZERO);
            
            log.info("获取首页统计数据成功: customerCount={}, businessCount={}, orderCount={}, totalRevenue={}", 
                    customerCount, businessCount, orderCount, totalRevenue);
                    
        } catch (Exception e) {
            log.error("获取首页统计数据失败", e);
            // 返回默认值
            stats.put("customerCount", 0);
            stats.put("businessCount", 0);
            stats.put("orderCount", 0);
            stats.put("totalRevenue", BigDecimal.ZERO);
        }
        
        return stats;
    }

    @Override
    public Map<String, Object> getRecentCustomers(Integer page, Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("pageSize", pageSize);
        params.put("offset", (page - 1) * pageSize);
        params.put("limit", pageSize);  // 为了兼容性保留limit参数
        params.put("sortBy", "created_at");
        params.put("sortOrder", "DESC");
        
        try {
            List<Map<String, Object>> customers = customerMapper.findCustomersWithDetails(params);
            Integer total = customerMapper.countCustomers(new HashMap<>());
            
            Map<String, Object> result = new HashMap<>();
            result.put("data", customers);
            result.put("total", total);
            result.put("page", page);
            result.put("size", pageSize);
            
            log.info("获取最近客户成功: 共{}条数据", customers.size());
            return result;
            
        } catch (Exception e) {
            log.error("获取最近客户失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("data", new ArrayList<>());
            result.put("total", 0);
            result.put("page", page);
            result.put("size", pageSize);
            return result;
        }
    }

    @Override
    public Map<String, Object> getPendingOrders(Integer page, Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("pageSize", pageSize);
        params.put("offset", (page - 1) * pageSize);
        params.put("limit", pageSize);  // 为了兼容性保留limit参数
        params.put("status", "待处理");
        params.put("sortBy", "created_at");
        params.put("sortOrder", "DESC");
        
        try {
            List<Map<String, Object>> orders = workOrderMapper.findWorkOrdersWithDetails(params);
            
            // 统计待处理工单总数
            Map<String, Object> countParams = new HashMap<>();
            countParams.put("status", "待处理");
            Integer total = workOrderMapper.countWorkOrders(countParams);
            
            Map<String, Object> result = new HashMap<>();
            result.put("data", orders);
            result.put("total", total);
            result.put("page", page);
            result.put("size", pageSize);
            
            log.info("获取待处理工单成功: 共{}条数据", orders.size());
            return result;
            
        } catch (Exception e) {
            log.error("获取待处理工单失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("data", new ArrayList<>());
            result.put("total", 0);
            result.put("page", page);
            result.put("size", pageSize);
            return result;
        }
    }
}